// pages/towxml/index.js
const app = getApp();
// const markdownpdf = require('markdown-pdf')
// JS

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  

  pdf(){
    
    // wx.showLoading({
    //   title: '导出中',
    //  })

    this.convertToImage()
    
  },

  async downloadCover(temp) {
    try {
      // 生成图片
      const tempFilePath = temp;
  
      // 检查授权
      const { authSetting } = await wx.getSetting();
      if (!authSetting['scope.writePhotosAlbum']) {
        await wx.authorize({ scope: 'scope.writePhotosAlbum' });
      }

  
      // 保存图片
      await wx.saveImageToPhotosAlbum({
        filePath: tempFilePath,
      });
  
      wx.showToast({ title: '保存成功' });
    } catch (error) {
      console.error('保存失败:', error);
      wx.showToast({ title: '保存失败', icon: 'none' });
    }
  },

  
  convertToImage() {
    this.setData({ loading: true });


    const query = wx.createSelectorQuery();
    query.select('#markdown-container').fields({
      size: true
    }, res => {
      if (!res || !res.width) {
        this.handleError();
        return;
      }

      const canvas = wx.createOffscreenCanvas({ type: '2d', width: 794, height: 2123 });
      const ctx = canvas.getContext('2d');

      // 绘制背景
      ctx.fillStyle = '#fff';
      ctx.fillRect(0, 0, 794, 2123);

      // 绘制解析后的内容
      this.drawMarkdown(ctx, this.data.content.children, res.width).then(() => {
        wx.canvasToTempFilePath({
          canvas,
          success: res => {
            this.setData({ imagePath: res.tempFilePath, loading: false });
            this.downloadCover(res.tempFilePath)
            // wx.showToast({ title: '转换成功' });
            // console.log(res.tempFilePath)
          },
          fail: this.handleError
        });
      }).catch(this.handleError);
    }).exec();
  },

  async drawMarkdown(ctx, nodes, maxWidth, y = 30) {
    // console.log(nodes)
    ctx.fillStyle = '#333';
    let currentY = y;

    for (const node of nodes) {
      if (node.type === 'text') {
        // 处理文本
        const lines = this.wrapText(node.text, ctx, maxWidth - 40);
        lines.forEach(line => {
          ctx.fillText(line, 20, currentY);
          currentY += 15; // 行高
        });
      } else if (node.type === 'image') {
        // 处理图片
        try {
          const tempPath = await this.downloadImage(node.attr.src);
          const img = await this.loadImage(tempPath);
          ctx.drawImage(img, 20, currentY, 100, 100); // 调整尺寸
          currentY += 100 + 10; // 图片高度加间距
        } catch (e) {
          console.error('图片加载失败:', e);
        }
      }
      // 递归处理子节点
      if (node.children) {
        currentY = await this.drawMarkdown(ctx, node.children, maxWidth, currentY);
      }
    }
    return currentY;
  },

  wrapText(text, ctx, maxWidth) {
    const words = text.split(' ');
    const lines = [];
    let currentLine = words[0] || '';

    for (let i = 1; i < words.length; i++) {
      const testLine = currentLine + ' ' + words[i];
      const metrics = ctx.measureText(testLine);
      if (metrics.width > maxWidth) {
        lines.push(currentLine);
        currentLine = words[i];
      } else {
        currentLine = testLine;
      }
    }
    lines.push(currentLine);
    return lines;
  },

  downloadImage(url) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url,
        success: res => resolve(res.tempFilePath),
        fail: reject
      });
    });
  },

  loadImage(src) {
    return new Promise((resolve, reject) => {
      const img = wx.createImage();
      img.src = src;
      img.onload = () => resolve(img);
      img.onerror = reject;
    });
  },

  handleError(err) {
    console.error('错误:', err);
    this.setData({ loading: false });
    wx.showToast({ title: '转换失败', icon: 'none' });
  },

  selectpdf(){
    // console.log(this.data.openId)
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'selectpdf',
        data: this.data.openId
      }
    }).then((resp) => {
      this.setData({
        fileID: resp.result.data[0],
      });
      // console.log(this.data.record.fileID)
      this.downloadFileOpen(this.data.fileID.fileID)
      wx.hideLoading();
    }).catch((e) => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  },
  downloadFileOpen(url){
    let link = url
    // console.log(link)
    //下载文件
    wx.cloud.downloadFile({
      fileID: link,
      success (res) {
        console.log(res)
        if (res.statusCode === 200) {
        const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
          showMenu:true, //关键点
            success: function (res) {
              wx.hideLoading();
              console.log('打开文档成功')
            }
          })
        }
      }
    })
  },
 


  selectCreateResume(){
    // console.log(this.data.openId)
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'selectCreateResume',
        data: this.data.openId
      }
    }).then((resp) => {
      this.setData({
        record: resp.result,
      });
      wx.cloud.getTempFileURL({
        fileList: [{
          fileID: resp.result.personalKeyInformation.img,
          maxAge: 60 * 60, // one hour
        }]
      }).then(res => {
        // get temp file URL
        // console.log(res.fileList[0].tempFileURL)
        this.setData({
          'record.personalKeyInformation.img': res.fileList[0].tempFileURL,
        });
        this.markdown(resp.result)
        console.log(this.data.record)
        wx.hideLoading();
      }).catch(error => {
        // handle error
      })

    }).catch((e) => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  },

  markdown(record) {
    // console.log(record.personalKeyInformation.img)
    let img = ''
    
    let personalKeyInformation = ''
    let evaluation = ''
    let education = ''
    let workExperience = ''
    let project = ''
    let qualificationCertificate = ''
    img = `![卷不动的小白](${record.personalKeyInformation.img})`
    personalKeyInformation = `
    \n姓名：${record.personalKeyInformation.userText}
    性别：${record.personalKeyInformation.genderText}
    出生年月：${record.personalKeyInformation.birthText}
    联系方式：${record.personalKeyInformation.phone}
    电子邮箱：${record.personalKeyInformation.email}
    求职意向：${record.personalKeyInformation.postText}
    `
    evaluation = `
    \n${record.evaluation.evaluation}
    `
    for(var j = 0; j < record.education.length; j++){
      education += `\n### ${record.education[j].schoolText} - ${record.education[j].majorText} - ${record.education[j].educationText}（${record.education[j].enrolText}-${record.education[j].graduateText}）
      \n- **主修课程**：${record.education[j].subject}` 
    };
    for(var j = 0; j < record.workExperience.length; j++){
      workExperience += `\n### ${record.workExperience[j].companyText} - ${record.workExperience[j].postText} （${record.workExperience[j].entryText}-${record.workExperience[j].resignText}）
      \n- **工作经历**：${record.workExperience[j].workContent}` 
    };
    for(var j = 0; j < record.project.length; j++){
      project += `\n### ${record.project[j].projectText} - ${record.project[j].roleText} （${record.project[j].entryText}-${record.project[j].resignText}）
      \n${record.project[j].projectContent}` 
    };
    for(var j = 0; j < record.qualificationCertificate.length; j++){
      qualificationCertificate += `
      \n- **证书**：${record.qualificationCertificate[j].certificate}` 
    };
    const contentMd = `\n# 个人简历
    \n---
    \n## 个人信息
    ${personalKeyInformation}
    \n---
    \n## 自我评价
    ${evaluation}
    \n---
    \n## 教育背景
    ${education}
    \n---
    \n## 工作经历
    ${workExperience}
    \n---
    \n## 项目经验
    ${project}
    \n---
    \n## 证书与荣誉
    ${qualificationCertificate}`;

 
    let result = app.towxml(contentMd, 'markdown', {
      theme: 'light'
    });
    // console.log(result)
    this.setData({
        content: result,
        md:contentMd
    });
     
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      'openId': wx.getStorageSync("openId")
    })
    wx.showLoading({
      title: '数据加载中...', // 这里设置提示词
      mask: true // 显示透明蒙层
    });
   
    this.selectCreateResume()
    // this.selectpdf()
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // wx.cloud.callFunction({
    //   name: 'quickstartFunctions',
    //   data: {
    //     type: 'deletepdf',
    //     data: this.data.openId
    //   },
    // }).then((resp) => {
    //   console.log(resp.result.data[0].fileID)
    //   wx.cloud.deleteFile({
    //     fileList: [resp.result.data[0].fileID], // 云存储中文件的fileID
    //   })
    // })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})